<template>
	<view class="page-container back-white pall-l col-box sb">
		<view class="content pcol-base radius-l">
			<!-- 订单信息 -->
			<view class="prow-base">
				<view class="row-box sb mb-base">
					<text>订单信息</text>
					<text class="s24 grey-light">订单编号：{{ merOrderNo }}</text>
				</view>
				<cd-petcard-order :pet="pet" :showShop="false" :showArrow="false"></cd-petcard-order>
			</view>
			<!-- 物流信息 -->
			<view class="mt-base">
				<view class="prow-base">
					<text>物流信息</text>
				</view>
				<!-- 配送方式 -->
				<view class="row-box sb" style="height: 92rpx;padding-left: 20rpx;">
					<view class="row-box">
						<text>配送方式</text>
						<text class="red">*</text>
					</view>
					<view class="row-box pcol-base" @click.stop="showType=true">
						<text class="s28">{{ type }}</text>
						<u-icon class="pall-base" name="arrow-right" color="#333333" size="30"></u-icon>
					</view>
				</view>
				<!-- 快递信息 -->
				<view v-if="type=='快递'">
					<!-- 快递公司 -->
					<view class="row-box sb" style="height: 92rpx;padding-left: 20rpx;">
						<view class="row-box">
							<text>快递公司</text>
							<text class="red">*</text>
						</view>
						<view class="row-box pcol-base" @click.stop="showExpress=true">
							<text v-if="express.name" class="s28">{{ express.name }}</text>
							<text v-else class="s28 grey-light">请选择快递公司</text>
							<u-icon class="pall-base" name="arrow-right" color="#333333" size="30"></u-icon>
						</view>
					</view>
					<!-- 快递单号 -->
					<view class="row-box sb" style="height: 92rpx;padding-left: 20rpx;">
						<view class="row-box">
							<text>快递单号</text>
							<text class="red">*</text>
						</view>
						<view class="row-box pcol-base">
							<input v-model="expressNo" type="text" :maxlength="24" placeholder="请输入或者扫描物流单号" style="text-align: right;" class="input" placeholder-class="placeholder">
							<u-icon class="pall-base" name="scan" color="#333333" size="32" @click="scan()"></u-icon>
						</view>
					</view>
				</view>
				<!-- 上传图片区域 -->
				<view v-else class="prow-base">
					<scroll-view scroll-x="true" style="white-space: nowrap;">
						<view class="pcol-l upload-grid">
							<view v-for="(item, index) in images" :key="index" class="upload-item">
								<image class="upload-image" :src="item" mode="aspectFill" @click.stop="previewImage(index, images)"></image>
								<view class="row-box center radius-circle icon-box">
									<u-icon name="close" color="#ffffff" size="28" :bold="true" @click.stop="removeImage(index)"></u-icon>
								</view>
							</view>
							<view v-if="images.length<limit" class="upload-item" @click="selectUploadHandle()">
								<image class="upload-image" src="/static/icon/upload.png" mode="aspectFill"></image>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<!-- 配送方式弹窗 -->
		<u-select v-model="showType" mode="single-column"
			:confirm-color="primaryColor" title="选择配送方式" :list="exTypeList" @confirm="selectType"
		>
		</u-select>
		<!-- 物流公司弹窗 -->
		<u-select v-model="showExpress" mode="single-column" value-name="shipperCode" label-name="shipperName"
			:confirm-color="primaryColor" title="选择物流公司" :list="exCompanyList" @confirm="selectExpress"
		>
		</u-select>
		
		<!-- 提交按钮 -->
		<view class="submit-button-box" style="padding-top: 40rpx;">
			<view class="submit-button back-primary" @click="submitHandle()">确定上传</view>
		</view>
	</view>
</template>

<script>
	import env from '@/utils/env.js'
	export default {
		data() {
			return {
				merOrderNo: '', // 订单编号
				pet: {}, // 宠物对象
				afterSaleId: '', // 售后id
				images: [], // 选择上传图片列表(临时地址)
				uploads: [],  // 照片列表(上传后)
				limit: 5, // 限制上传数量
				qntoken: '',  // 七牛云上传token
				
				type: '快递', // 快递0 汽运1 空运2
				showType: false, // 是否展示配送方式弹窗
				exTypeList: [ {value: 0, label: '快递'}, {value: 0, label: '汽运'}, {value: 0, label: '空运'}], // 配送方式列表
				showExpress: false, // 是否展示物流弹窗
				exCompanyList: [], // 物流公司列表
				express: {}, // 快递公司 编码和名字
				expressNo: '', // 快递单号
			};
		},
		computed: {
			// 提交图片凭证，最多5张 将已选择图片地址转为字符串，多个逗号分割
			submitImages()  {
				return this.uploads.join(',')
			},
		},
		watch: {
			// 侦听图片上传后地址列表
			uploads(newValue, oldValue) {
				if ((newValue.length == this.images.length) && this.images.length!=0) {
					// 上传完所有图片
					// 调用反馈接口
					this.submit()
				}
			},
		},
		onLoad(options) {
			this.merOrderNo = options.id
			this.pet = JSON.parse(decodeURIComponent(options.pet))
			this.afterSaleId = options.id2
			// 获取七牛上传使用TOKEN
			this.getUploadToken()
			// 获取物流公司列表
			this.getExpressCompanyList()
		},
		methods: {
			// 选择上传前
			async selectUploadHandle() {
				this.images = [...this.images, ...await this.chooseImages(this.limit - this.images.length)]
			},
			
			// 选择配送方式
			selectType(e) {
				this.type = e[0].label
			},
			
			// 选择物流公司
			selectExpress(e) {
				this.express['code'] = e[0].value
				this.express['name'] = e[0].label
			},
			
			// 扫码
			scan() {
				uni.scanCode({
					success: res => {
						console.log('扫码：', res)
						this.expressNo = res.result
					}
				})
			},
			
			// 提交申请处理
			submitHandle() {
				if (this.type=='快递') {
					if (!this.express.code) {
						return uni.showToast({
							icon: 'none',
							title: '未选择物流公司！'
						})
					} else if (!this.expressNo) {
						return uni.showToast({
							icon: 'none',
							title: '未填写物流单号！'
						})
					}
				} else if (!this.images) {
					return uni.showToast({
						icon: 'none',
						title: '未选择物流凭证！'
					})
				}
				
				uni.showLoading({
					title: '提交中...',
					mask: true
				})
				// 获取临时文件列表长度
				const length = this.images.length
				if (length > 0) { // 如果用户选择了图片
					// 将选择的图片文件上传到存储空间（循环调用上传api）获得图片的访问地址
					this.images.forEach((filePath, index) => {
						let pathArr = filePath.split('.')
						// 获得唯一标识码
						let uniqueCode = this.generateUUID()
						// case 'ECN': uploadURL = 'https://up.qiniup.com'
						// case 'NCN': uploadURL = 'https://up-z1.qiniup.com'
						// case 'SCN': uploadURL = 'https://up-z2.qiniup.com'
						// case 'NA': uploadURL = 'https://up-na0.qiniup.com'
						// case 'ASG': uploadURL = 'https://up-as0.qiniup.com'
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com',
							filePath: filePath,
							name: 'file',
							formData: {
								'key': uniqueCode + '.' + pathArr[pathArr.length-1],
								'token': this.qntoken,
							},
							success: (res) => {
								console.log('uni.uploadFile', res)
								let strToObj = JSON.parse(res.data)
								let backUrl = env.imageUrl + strToObj.key
								// 处理上传成功后的返回值
								this.uploads.push(backUrl)
							},
							fail: (err) => {
								console.log('uni.uploadFile', err)
							}
						})
					})
				} else { // 用户未选择图片
					// 调用提交申请
					this.submit()
				}
			},
			// 提交申请
			submit() {
				let params = {}
				params['type'] = '3'
				params['id'] = this.afterSaleId
				if (this.express.code) params['expressCode'] = this.express.code
				if (this.expressNo) params['expressNo'] = this.expressNo
				if (this.uploads.length) params['image'] = this.uploads.join(',')
				this.$api.AddExpress(params).then(res => {
					console.log('AddExpress-success', res)
					uni.hideLoading()
					if (res.data.code == 200) {
						uni.showToast({
							icon: 'none',
							title: '上传成功！',
							success: () => {
								setTimeout(() => {
									uni.navigateBack({
										delta: 1,
										success: () => {
											uni.startPullDownRefresh()
										}
									})
								}, 300)
							}
						})
					}else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('AddExpress-fail', err)
					uni.hideLoading()
				})
			},
			
			// 获取物流公司列表
			getExpressCompanyList() {
				this.$api.GetExpressCompanyList().then(res => {
					console.log('GetExpressCompanyList-success', res)
					if (res.data.code == 200) {
						this.exCompanyList = res.data.data.records
					}else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				}).catch(err => {
					console.log('GetExpressCompanyList-fail', err)
				})
			},
		},
	}
</script>

<style lang="scss">
	// 订单信息
	.content {
		box-shadow: 0rpx 4rpx 46rpx 0rpx rgba(227,230,229,0.8);
		padding-bottom: 0;
	}
</style>
